package com.linln.wxapi;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.linln.common.enums.TypeEnum;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.AreaCount;
import com.linln.modules.member.domain.MemberCollect;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.AreaCountService;
import com.linln.modules.member.service.MemberCollectService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.system.domain.Dict;
import com.linln.modules.system.service.DictService;
import com.linln.modules.tribe.domain.Tribe;
import com.linln.modules.tribe.domain.Tribetype;
import com.linln.modules.tribe.service.TribeService;
import com.linln.modules.tribe.service.TribetypeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
 * 部落接口
 * @author hct
 *
 */
@Api(value="部落接口")
@RestController
@RequestMapping("/wx/tribe/{area}")
public class WxApiTribeController {
	  @Autowired
	  private AreaCountService areaCountService;
	
	 @Autowired
	 private TribetypeService tribetypeService;
	 
	 @Autowired
	 private DictService dictService;
	 
	 @Autowired
	 private TribeService tribeService;
	 
	 @Autowired
	 private MemberInfoService memberService;
	 
	  @Autowired
	  private MemberCollectService memberCollectService;
	
	 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
	  //获取我的部落列表
	 @RequestMapping(value ="tribelist",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo tribelist(@PathVariable String area, Long memeberid) {
         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching();
                     //.withMatcher("type_name", match -> match.contains())
             Tribetype tribetype=new Tribetype();
             tribetype.setArea(area);
            // tribetype.setMemeberid(memeberid);
             // 获取数据列表
             Example<Tribetype> example = Example.of(tribetype, matcher);
             Sort sort = new Sort(Sort.Direction.ASC, "updateDate");
             List<Tribetype> list = tribetypeService.getListByExample(example, sort);
             return ResultVoUtil.success(list);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	  //推荐部落列表
		 @RequestMapping(value ="recotribelist",method={RequestMethod.POST,RequestMethod.GET})
	     @ResponseBody
	     public ResultVo recotribelist(@PathVariable String area) {
	         try {
	         	// 创建匹配器，进行动态查询匹配
	             ExampleMatcher matcher = ExampleMatcher.matching();
	                     //.withMatcher("type_name", match -> match.contains())
	             Tribetype tribetype=new Tribetype();
	             tribetype.setArea(area);
	             // 获取数据列表
	             Example<Tribetype> example = Example.of(tribetype, matcher);
	             Sort sort = new Sort(Sort.Direction.ASC, "updateDate");
	             List<Tribetype> list = tribetypeService.getListByExample(example, sort);
	             return ResultVoUtil.success(list);
	         } catch (Exception e) {
	             this.logger.error(e.getMessage(), e);
	             return ResultVoUtil.error("接口异常"); 
	         }
	     }
	
		 
		 //按照类型获取部落列表
		 @RequestMapping(value ="tribelistbytype",method={RequestMethod.POST,RequestMethod.GET})
	     @ResponseBody
	     public ResultVo tribelistbytype(@PathVariable String area,Long tribetypeid) {
	         try {
	         	// 创建匹配器，进行动态查询匹配
	             ExampleMatcher matcher = ExampleMatcher.matching();
	                     //.withMatcher("type_name", match -> match.contains())
	             Tribetype tribetype=new Tribetype();
	             tribetype.setArea(area);
	             tribetype.setTribetype(tribetypeid);
	             // 获取数据列表
	             Example<Tribetype> example = Example.of(tribetype, matcher);
	             Sort sort = new Sort(Sort.Direction.ASC, "updateDate");
	             List<Tribetype> list = tribetypeService.getListByExample(example, sort);
	             return ResultVoUtil.success(list);
	         } catch (Exception e) {
	             this.logger.error(e.getMessage(), e);
	             return ResultVoUtil.error("接口异常"); 
	         }
	     }
	 //添加部落
	 @RequestMapping(value ="addtribe",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo addtribe(Tribetype tribetype) {
         try {
        	 tribetypeService.save(tribetype);
             return ResultVoUtil.success("添加部落成功");
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	 
	 //获取部落类别
	 
	 @RequestMapping(value ="tribetypelist",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo getDict() {
         try {
           String tribename="TRIBE_TYPE";
        	 Dict dict= dictService.getByNameOk(tribename);
        	 List<Map<String,String>> dictlist= getDictlist(dict.getValue());
             return ResultVoUtil.success(dictlist);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	 
	 private List<Map<String,String>> getDictlist(String value) {
		 List<Map<String,String>> dictList=new ArrayList<Map<String,String>>();
		 String values[]=value.split(",");
		 for(String dictvalue:values) {
			 String dictvalues[]=dictvalue.split(":");
			 if(null!=dictvalues&&dictvalues.length>0) {
				 HashMap<String,String> di=new HashMap<String,String>();
				 di.put(dictvalues[0], dictvalues[1]);
				 dictList.add(di);
			 }
		 }
		 return dictList;
	 }
	 
	 //获取话题列表
	 @RequestMapping(value ="tribetopiclist",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo tribetopiclist(@PathVariable String area,Integer pageNumber,Integer pageSize) {
         try {
             ExampleMatcher matcher = ExampleMatcher.matching();
             Tribe tribe=new Tribe();
             tribe.setArea(area);
             Example<Tribe> example = Example.of(tribe, matcher);
             Page<Tribe> pagelist = tribeService.getPageList(example,pageNumber,pageSize);
             
             return ResultVoUtil.success(pagelist.getContent());
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 //获取话题列表
	 @RequestMapping(value ="topiclistBytribe",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo tribetopiclist(@PathVariable String area,Long tribeid,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
  			 @RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize) {
         try {
             ExampleMatcher matcher = ExampleMatcher.matching();
             Tribe tribe=new Tribe();
             tribe.setArea(area);
             tribe.setTribeid(tribeid); 
             Example<Tribe> example = Example.of(tribe, matcher);
             Page<Tribe> pagelist = tribeService.getPageList(example,pageNumber,pageSize);
             
             return ResultVoUtil.success(pagelist.getContent());
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	 
	 
	 
	 /*
	  * 根据话题编号获取话题
	  */
	 @RequestMapping(value ="gettribeByid",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo gettribeByid(Long tribeid) {
         try {
        	 Tribe tribe = tribeService.getById(tribeid);
        	 tribe.setVisitnum( tribe.getVisitnum()+1);
        	 tribeService.save(tribe);
             return ResultVoUtil.success(tribe);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	 
	 /*
	  * 根据话题编号获取话题
	  */
	 @RequestMapping(value ="createTribe",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo createTribe(Tribe tribe,@PathVariable String area) {
		 
	    	Gson gson=new Gson();
	    	String ss=gson.toJson(tribe);
	    	System.out.println(DateUtils.format(new Date())+">>>>>>>>>>>>createTribe >>"+ss);

         try {
          Long  tribeid = tribe.getTribeid();
          if(null!=tribeid) {
          Tribetype tribetype=tribetypeService.getById(tribeid);
          tribe.setTribetitle(tribetype.getTribetitle());
          tribe.setTribetype(tribetype.getTribetype());
          }
          Long memberid=tribe.getMemberid();
          if(null!=memberid) {
          MemberInfo memberInfo= memberService.getById(memberid);
          tribe.setPersonname(memberInfo.getNickname());
          tribe.setPersonhead(memberInfo.getHeadimg());
          }
          tribe.setCommentnum(0);
          tribe.setHelpnum(0);
          tribe.setCreateDate(new Date());
          tribe.setOppose(0);
          tribe.setVisitnum(0);
          tribe.setZannum(0);
          tribe=tribeService.save(tribe);
             return ResultVoUtil.success(tribe);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
	 
	 /*
	  * 更新话题点赞数量
	  */
	 @RequestMapping(value ="updHelpnum",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo updHelpnum(Long tribeid) {
		Tribe tribe= tribeService.getById(tribeid);
		tribe.setHelpnum(tribe.getHelpnum()+1);
		tribe=tribeService.save(tribe);
		 return ResultVoUtil.success(tribe);
     }
	 
	 /*
	  * 更新话题评论数量
	  */
	 @RequestMapping(value ="updcommentnum",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo updCommentnum(Long tribeid) {
		Tribe tribe= tribeService.getById(tribeid);
		tribe.setCommentnum(tribe.getCommentnum()+1);
		tribe=tribeService.save(tribe);
		 return ResultVoUtil.success(tribe);
     }
	 

	 /*
	  * 更新话题反对
	  */
	 @RequestMapping(value ="updoppsenum",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo updOppsenum(Long tribeid) {
		Tribe tribe= tribeService.getById(tribeid);
		tribe.setOppose(tribe.getOppose()+1);
		tribe=tribeService.save(tribe);
		 return ResultVoUtil.success(tribe);
     }
	 
	 /* * 更新话题收藏状态
	  */
	 @RequestMapping(value ="updcollectstate",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo updcollectstate(@PathVariable String area,Long tribeid,Long memberId) {
		 try {
	        	
	        	MemberCollect collect= memberCollectService.getByMemberIdAndTypeId(memberId,TypeEnum.TRIBE.getCode(), tribeid);
	             
	        	if(collect!=null && collect.getId()>0){
	        		memberCollectService.delCollect(collect.getId());
	        		//TODO对应的消息数量减一
	        		tribeService.updateIsCollectSubById(tribeid);
	        		//取消收藏
	        	}else{
	        		collect=new MemberCollect();
	        		collect.setType(TypeEnum.TRIBE.getCode());
	        		collect.setTypeId(tribeid);
	        		collect.setArea(area);
					collect.setCreateDate(new Date());
					collect.setUpdateDate(new Date());
	        		collect.setMemberId(memberId);
	             	collect = memberCollectService.save(collect);
	             	tribeService.updateIsCollectAddById(tribeid);
	                //对应的消息数量加1
	        		AreaCount count=areaCountService.findByArea(area);
	        		if(count==null) {
	        			count=new AreaCount();
	        			count.setArea(area);
	        			count.setMessage_collectnum(1); 
	        			areaCountService.save(count);
	        		}else {
	        			areaCountService.updateCollectByArea(area);
	        		}
	        	}         	
	        	 return ResultVoUtil.success(collect);
	        } catch (Exception e) {
	        	return ResultVoUtil.error("失败"); 
	        }
		 
		 
		 
		 
		 
		 
		 
     }
	 
	 
	 
	  /**
	     * 收藏及取消收藏
	     * @param area 区域
	     * @return
	     */
	    @ApiOperation(value = "是否收藏",  notes = "是否收藏")
	    @RequestMapping(value = "iscollect",method= {RequestMethod.POST,RequestMethod.GET})
	    @ResponseBody
	    public ResultVo mymessagecollect(@PathVariable String area,Long tribeId, Long memberId) {
	       
	        try {
	        	MemberCollect collect= memberCollectService.getByMemberIdAndTypeId(memberId,TypeEnum.TRIBE.getCode(), tribeId);
	            
	        	if(collect!=null && collect.getId()>0){
	         		return ResultVoUtil.success(1);
	        	}       
	        	return ResultVoUtil.success(0); 
	           } catch (Exception e) {
	            	return ResultVoUtil.error("失败"); 
	         }

	   }	
	    
	    /**
		 * 查询话题信息
		 * @param area 区域

		 * @return
		 */
		@ApiOperation(value = "查询信息",  notes = "查询信息")
		@RequestMapping(value = "search",method={RequestMethod.POST,RequestMethod.GET})
		@ResponseBody
		public ResultVo searchMessage(@PathVariable String area,String keyword,
				Integer type,
				@RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
				@RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize) {
			System.out.println(DateUtils.format(new Date())+"list area>>"+area+">>>title=="+keyword);

			try {
				// 创建匹配器，进行动态查询匹配
				if(type==2) {
				ExampleMatcher matcher = ExampleMatcher.matching()
						.withMatcher("description", match -> match.contains());
				Tribe baseinfo=new Tribe();
				baseinfo.setArea(area);
				if(StringUtils.isNoneBlank(keyword)){
					baseinfo.setDescription(keyword);
				}				
				// 获取话题列表
				Example<Tribe> example = Example.of(baseinfo, matcher);
				Page<Tribe> list = tribeService.getPageList(example, pageNumber,pageSize);
                
				if(list.getContent()==null || list.getContent().size()==0) {
					return ResultVoUtil.success("暂无数据");
				}else {
					Map<String,Object> map=new HashMap<String,Object>();
					map.put("list", list.getContent());
					map.put("pageNumber", list.getPageable().getPageNumber()+1);
					map.put("pageSize", list.getPageable().getPageSize());
					return ResultVoUtil.success(map);
				}
				}else if(type==1) {
					ExampleMatcher matcher = ExampleMatcher.matching()
							.withMatcher("tribetitle", match -> match.contains());
					Tribetype baseinfo=new Tribetype();
					baseinfo.setArea(area);
					if(StringUtils.isNoneBlank(keyword)){
						baseinfo.setTribetitle(keyword);
					}				
					// 获取话题列表
					Example<Tribetype> example = Example.of(baseinfo, matcher);
					Page<Tribetype> list = tribetypeService.getPageList(example, pageNumber,pageSize);
	                
					if(list.getContent()==null || list.getContent().size()==0) {
						return ResultVoUtil.success("暂无数据");
					}else {
						Map<String,Object> map=new HashMap<String,Object>();
						map.put("list", list.getContent());
						map.put("pageNumber", list.getPageable().getPageNumber()+1);
						map.put("pageSize", list.getPageable().getPageSize());
						map.put("pageCount", list.getTotalPages());
		                map.put("allCount", list.getTotalElements());
						return ResultVoUtil.success(map);
					}
				}
				return ResultVoUtil.success("暂无数据");

			} catch (Exception e) {
				this.logger.error(e.getMessage(), e);
				return ResultVoUtil.error("接口异常");

			}

		} 
	    
}
